package com.ljy.jymail.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.ljy.common.exception.NoStockException;
import com.ljy.common.to.mq.OrderTo;
import com.ljy.common.to.mq.SeckillOrderTo;
import com.ljy.common.utils.R;
import com.ljy.common.vo.MemberRespVo;
import com.ljy.jymail.order.constant.OrderConstant;
import com.ljy.jymail.order.entity.OrderItemEntity;
import com.ljy.jymail.order.entity.PaymentInfoEntity;
import com.ljy.jymail.order.enume.OrderStatusEnum;
import com.ljy.jymail.order.feign.CartFeignService;
import com.ljy.jymail.order.feign.MemberFeignService;
import com.ljy.jymail.order.feign.ProductFeignService;
import com.ljy.jymail.order.feign.WmsFeignService;
import com.ljy.jymail.order.interceptor.LoginUserInterceptor;
import com.ljy.jymail.order.service.OrderItemService;
import com.ljy.jymail.order.service.PaymentInfoService;
import com.ljy.jymail.order.to.OrderCreateTo;
import com.ljy.jymail.order.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljy.common.utils.PageUtils;
import com.ljy.common.utils.Query;

import com.ljy.jymail.order.dao.OrderDao;
import com.ljy.jymail.order.entity.OrderEntity;
import com.ljy.jymail.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;



@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {



    private ThreadLocal<OrderSubmitVo> submitVoThreadLocal = new ThreadLocal<>();

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    WmsFeignService WmsFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    PaymentInfoService paymentInfoService;



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }


    /*给订单确认页返回需要用的数据*/
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        //从拦截器中获取用户Id
        MemberRespVo memberRespVo = LoginUserInterceptor.LoginUser.get();

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //异步
        CompletableFuture<Void> addressExecutor = CompletableFuture.runAsync(() -> {
            //获取收货地址列表
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            confirmVo.setAddress(address);
        }, executor);
        CompletableFuture<Void> itemsExecutor = CompletableFuture.runAsync(() -> {
            //远程查询购物车所有选中的购物项
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> items = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(items);
        }, executor).
                //查询库存信息
                thenRunAsync(()->{
                    List<OrderItemVo> items = confirmVo.getItems();
                    List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
                    R skuHasStock = WmsFeignService.getSkuHasStock(collect);
                    List<SkuStockVo> data = skuHasStock.getData(new TypeReference<List<SkuStockVo>>(){});
                    if (data!=null){
                        Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                        confirmVo.setStocks(map);
                    }
                },executor);
        CompletableFuture<Void> integrationExecutor = CompletableFuture.runAsync(() -> {
            //feign在此之前会调用
            //查询用户积分
            RequestContextHolder.setRequestAttributes(requestAttributes);
            Integer integration = memberRespVo.getIntegration();
            confirmVo.setIntegration(integration);
        }, executor);

        //TODO:防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");

        confirmVo.setOrderToken(token);
        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId(),token,30, TimeUnit.MINUTES);
        CompletableFuture.allOf(itemsExecutor, integrationExecutor, addressExecutor).get();


        return confirmVo;
    }


    /*
    * 下单方法    创建订单，验令牌，验证价格，锁库存
     * */

    @Override
    @Transactional
//    @GlobalTransactional
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo orderSubmitVo)  {


        SubmitOrderResponseVo response = new SubmitOrderResponseVo();
        response.setCode(0);//0-没有问题
        MemberRespVo memberRespVo = LoginUserInterceptor.LoginUser.get();
        submitVoThreadLocal.set(orderSubmitVo);
        //原子验令牌
        String orderToken = orderSubmitVo.getOrderToken();//页面提交的令牌
        //令牌的对比和删除需要保持一致性--lua脚本
        //0-令牌失败 1-删除成功
        String script =
                "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end ";
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);
        if (result==0){
            //令牌验证失败
            response.setCode(1);
            return response;
        }else {
            //删除成功
            //创建订单，订单项等信息
            OrderCreateTo order = createOrder();
            //验证价格
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = new BigDecimal(0);
            //只要差价小于0.01就判断他们相同
            if (Math.abs(payAmount.subtract(payPrice).doubleValue())<0.01||true) {
                //3、保存订单
                saveOrder(order);
                //4、库存锁定 只要有异常，就回滚订单数据
                //需要的数据： 订单号，所有订单项(skuId,skuName,num)
                WareSkuLockVo lockVo = new WareSkuLockVo();
                List<OrderItemVo> orderItemVo = order.getOrderItems().stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setTitle(item.getSkuName());
                    return itemVo;
                }).collect(Collectors.toList());

                lockVo.setOrderSn(order.getOrder().getOrderSn());
                lockVo.setLocks(orderItemVo);
                //TODO 远程锁库存
                //为了保证高并发,库存服务自己回滚 通过mq消息服务发送消息，
                // 告诉其他服务自己的情况，让其他服务进行解决，使用延时队列
                R r = WmsFeignService.orderLockStock(lockVo);
                if (r.getCode() == 0){
                    //锁成功
                    response.setOrder(order.getOrder());
                    //订单创建成功，发送消息给RabbitMq
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
                    return response;
                }else {
                    //锁失败
//                    response.setCode(3);//3-库存出现问题
//                    return response;
//                    System.out.println("-----------------------r.getCode()："+r.getCode());
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }
//                throw
            }else {
                response.setCode(2);//2-金额对比失败
                return response;
            }

            //锁库存
        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {

        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order_sn;
    }

    /*
    * 关单：
    *   1、查看订单是否支付
    *   2、没支付的订单关闭，状态修改
    * */
    @Override
    public void closeOrder(OrderEntity entity) {
        OrderEntity orderEntity = this.getById(entity.getId());
        //判断订单状态
        if (orderEntity.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())){
//            System.out.println("要修改的订单状态");
            //进行关单
            OrderEntity update = new OrderEntity();
            update.setId(orderEntity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);
            //给mq发送消息，通知解锁库存
            try {
                //保证消息百分百发送出去，给每个发送的消息都做日志记录
                //TODO:定期扫描数据库，将失败的消息重新发送
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
            }catch (Exception e) {
                //容错方法 TODO 出现问题后，将没发送成功的消息进行重试发送

            }
        }
    }


    /*
    * 获取当前订单的支付信息
    * */
    @Override
    public PayVo getOrderPay(String orderSn) {

        OrderEntity orderByOrderSn = this.getOrderByOrderSn(orderSn);
        PayVo payVo = new PayVo();

        BigDecimal decimal = orderByOrderSn.getPayAmount().setScale(2, BigDecimal.ROUND_UP);//有小数向上取值
        payVo.setOut_trade_no(orderByOrderSn.getOrderSn());
        payVo.setTotal_amount(decimal.toString());
        List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        String skuName = order_sn.get(0).getSkuName();
        payVo.setSubject(skuName);
        payVo.setBody(order_sn.get(0).getSkuAttrsVals());
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.LoginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberRespVo.getId()).orderByDesc("id"));
        List<OrderEntity> collect = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(order_sn);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(collect);

        return new PageUtils(page);
    }

    /*
    * 处理支付宝的支付结果
    * */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        //1、保存交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());//流水号
        infoEntity.setOrderSn(vo.getOut_trade_no());//订单号
        infoEntity.setPaymentStatus(vo.getTrade_status());//订单状态
        infoEntity.setCallbackTime(vo.getNotify_time());//通知回调时间
        paymentInfoService.save(infoEntity);

        //2、修改订单状态信息  TRADE_SUCCESS TRADE_FINISHED TRADE_CLOSED
        if (vo.getTrade_status().equals("TRADE_SUCCESS")||vo.getTrade_status().equals("TRADE_FINISHED")){
            //修改订单状态
            String outTradeNo = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(outTradeNo,OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    @Override
    public void updateOrderStatus(String orderSn) {
        this.baseMapper.updateOrderStatus(orderSn,OrderStatusEnum.PAYED.getCode());
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrder) {
        //TODO: 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrder.getOrderSn());
        orderEntity.setMemberId(seckillOrder.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal totalPrice = seckillOrder.getSeckillPrice().multiply(new BigDecimal("" + seckillOrder.getNum()));
        orderEntity.setPayAmount(totalPrice);
        //TODO 收货地址
        this.save(orderEntity);
        //保存订单项信息

        OrderItemEntity itemEntity = new OrderItemEntity();
        itemEntity.setOrderSn(seckillOrder.getOrderSn());
        itemEntity.setRealAmount(totalPrice);

        itemEntity.setSkuQuantity(seckillOrder.getNum());

        //TODO: productFeignService.getSpuInfoBySkuId()
        orderItemService.save(itemEntity);
    }

    //保存订单数据
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }


    /*
    * @TODO 创建订单
    * @author ljy
    * @time 2022-02-10 10:36:51
    * @method createOrder
    * @param param
    * @return com.ljy.jymail.order.to.OrderCreateTo
    */
    private OrderCreateTo createOrder(){
        OrderCreateTo createTo = new OrderCreateTo();
        OrderSubmitVo submitVo = submitVoThreadLocal.get();
        //1、生成订单号 TODO 雪花算法
        String orderSn = IdWorker.getTimeId();
        //创建订单号
        OrderEntity orderEntity = buildOrder(submitVo, orderSn);
        //2、获取到所有的订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);
        //3、计算价格相关的数据
        computePrice(orderEntity, itemEntities);
        createTo.setOrder(orderEntity);
        createTo.setOrderItems(itemEntities);
        return createTo;
    }

    /*计算价格相关数据*/
    private OrderEntity computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        //订单价格相关数据 总额 应付额 运费
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");//优惠劵
        BigDecimal integration = new BigDecimal("0.0");//积分
        BigDecimal promotion = new BigDecimal("0.0");//折扣
        BigDecimal gift = new BigDecimal("0.0");//总积分
        BigDecimal growth = new BigDecimal("0.0");//成长值


        //订单总额：叠加每一个订单项的信息
        for (OrderItemEntity entity:itemEntities){
            coupon = coupon.add(entity.getCouponAmount());
            integration = integration.add(entity.getIntegrationAmount());
            promotion = promotion.add(entity.getPromotionAmount());
            total = total.add(entity.getRealAmount());
            gift = gift.add(new BigDecimal(entity.getGiftIntegration().toString()));
            growth = growth.add(new BigDecimal(entity.getGiftGrowth().toString()));
        }
        //1、订单价格相关
        orderEntity.setTotalAmount(total);//总额
        //应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()==null?new BigDecimal(0):orderEntity.getFreightAmount()));//加上运费

        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);

        //积分等信息
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());

        //删除状态
        orderEntity.setDeleteStatus(0);//0-未删除
        return orderEntity;
    }

    //构建订单收货信息
    private OrderEntity buildOrder(OrderSubmitVo submitVo, String orderSn) {
        MemberRespVo memberRespVo = LoginUserInterceptor.LoginUser.get();
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);
        //设置会员信息
        entity.setMemberId(memberRespVo.getId());
        //获取收货信息
//        R fare = WmsFeignService.getFair(submitVo.getAddrId());
//        FareVo fareResp = fare.getData(new TypeReference<FareVo>() {});
//        entity.setFreightAmount(fareResp.getFare());//运费
//        entity.setReceiverCity(fareResp.getAddress().getCity());//城市
//        entity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());//默认地址
//        entity.setReceiverName(fareResp.getAddress().getName());//名字
//        entity.setReceiverPhone(fareResp.getAddress().getPhone());//手机号
//        entity.setReceiverPostCode(fareResp.getAddress().getPostCode());//邮编
//        entity.setReceiverProvince(fareResp.getAddress().getProvince());//市区
//        entity.setReceiverRegion(fareResp.getAddress().getRegion());//区域信息
//      entity.setReceiveTime(); TODO 收货时间

        //设置订单相关状态信息
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());//待付款状态
        entity.setAutoConfirmDay(7);//自动确认时间
        return entity;
    }

    //构建所有订单项数据
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //最后一次确定每个购物项的价格
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if (currentUserCartItems!=null && currentUserCartItems.size() > 0){
            List<OrderItemEntity> itemEntities = currentUserCartItems.stream().map(cartItem -> {
                //构建订单项
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    //构建某一个订单项信息
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        //构建订单项
        OrderItemEntity itemEntity = new OrderItemEntity();
        //1、订单信息：订单号
        //2、商品SPU信息
        Long skuId = cartItem.getSkuId();
        R spuInfoBySkuId = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfo = spuInfoBySkuId.getData(new TypeReference<SpuInfoVo>() {});
        itemEntity.setSpuId(spuInfo.getId());
        itemEntity.setSpuBrand(spuInfo.getBrandId().toString());
        itemEntity.setSpuName(spuInfo.getSpuName());
        itemEntity.setCategoryId(spuInfo.getCatalogId());
        //3、商品SKU信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttrValues(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        //4、优惠信息【忽略】
        //5、积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());//成长积分
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());

        //6、订单项价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));//促销优惠价
        itemEntity.setCouponAmount(new BigDecimal("0"));//优惠劵
        itemEntity.setIntegrationAmount(new BigDecimal("0"));//积分
        //当前订单项的实际金额
        BigDecimal orign = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal amount = orign.subtract(itemEntity.getPromotionAmount()).subtract(itemEntity.getCouponAmount()).subtract(itemEntity.getIntegrationAmount());

        itemEntity.setRealAmount(amount);
        return itemEntity;
    }

}